package binary_search_tree

type tBinaryNode struct {
	value interface{}
	parent *tBinaryNode
	left *tBinaryNode
	right *tBinaryNode
}

func newBinaryNode(value interface{}) *tBinaryNode {
	return &tBinaryNode{
		value: value,
		left: nil,
		right: nil,
	}
}

func (me *tBinaryNode) childrenCount() int {
	left := me.left
	right := me.right

	if left == nil && right == nil {
		return 0
	}

	if left == nil || right == nil {
		return 1
	}

	return 2
}

func (me *tBinaryNode) LChild(node *tBinaryNode) {
	me.left = node
	if node != nil {
		node.SetParent(me)
	}
}

func (me *tBinaryNode) SetParent(parent *tBinaryNode) {
	if me.parent == parent {
		return
	}

	if me.parent != nil {
		if me.parent.left == me {
			me.parent.left = nil
		} else if me.parent.right == me {
			me.parent.right = nil
		}
	}

	me.parent = parent
}

func (me *tBinaryNode) RChild(node *tBinaryNode) {
	me.right = node
	if node != nil {
		node.SetParent(me)
	}
}